package com.cande.loki.exercise.agentproxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @auther ROCK CODER
 * @DATE 2022/6/24 8:44
 * @Description
 */
public class ProxyEaxmple {
    static interface Car{
        void runing();
    }
    static class Bus implements Car{

        @Override
        public void runing() {
            System.out.println("this is bus");
        }
    }
    static class JDKProxy implements InvocationHandler {
        private Object target;

        public Object getInstance(Object target){
            this.target = target;
            return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("马上要开始执行了");
            System.out.println(proxy.getClass().getName());
            //多次执行是因为idea调用tostring（）方法的原因
            System.out.println(method.getName());
            Object result = method.invoke(target,args);
            return result;
        }
    }

    public static void main(String[] args) {
        JDKProxy jdkProxy = new JDKProxy();
        Car car = (Car) jdkProxy.getInstance(new Bus());
        car.runing();
    }

}
